<script lang="ts" setup>
import { onBeforeUnmount, onMounted, watch, ref, reactive } from 'vue';
//  defineProps,
import { useRouter } from 'vue-router';
import { openWindow } from '@vben/utils';
// import Player from 'xgplayer';
// import Plyr from "plyr";
// import "plyr/dist/plyr.css";
// import LivePlayer from '@liveqing/liveplayer-v3'
import {
  ElMessage,
  ElSplitter,
  ElSplitterPanel
} from "element-plus";
import AMapLoader from "@amap/amap-jsapi-loader";
import webrtcPlayer from '#/components/WebrtcPlayer.vue'
import { mapSetting } from "#/api/map";
const getImageUrl = (name: string) => {
  return new URL(`../../../../../assets/${name}`, import.meta.url).href
}
// import Hls from 'hls.js';
const props = defineProps({ airportData: Object, loading: Boolean });
const router = useRouter();
// const getSpan = (index) => {
//   switch (props.changeViewId) {
//     case 1: {
//       return 24;
//     }
//     case 2: {
//       return 12;
//     }
//     case 3: {
//       return index === 0 ? 16 : 8;
//     }
//     default: {
//       return 8;
//     }
//   }
// };
const hlsInstances: Record<number, Hls> = {};

const navToClick = () => {
  const nav = '/dronemonitoringDetail';
  if (nav?.startsWith('http')) {
    openWindow(nav);
    return;
  }
  if (nav?.startsWith('/')) {
    router.push(nav).catch((error) => {
      console.error('Navigation failed:', error);
    });
  } else {
    console.warn(`Unknown URL for navigation item: ${nav.title} -> ${nav.url}`);
  }
};
const video_option = {
  loadSprite: false,
  iconUrl: '/static/plyr.svg'
}
let player = '';
let player2 = '';
const videoRef = ref(null)
const videoRef2 = ref(null)
let videoAddress = ref(null);
// let videoAddress = ref('http://47.99.37.125/index/api/webrtc?app=live&stream=8UUXN2800A00HX&type=play')
let videoAddress2 = ref(null);
let checkInterval;
const to_video = (() => {
  videoAddress.value = props.airportData.droneVideoAddress
  videoAddress2.value = props.airportData.videoAddress
  // if (player) player.release()
  // player = new ZLMRTCClient.Endpoint({
  //   element: videoRef.value,  // 绑定video元素
  //   zlmsdpUrl: videoAddress.value,  // WebRTC流地址
  //   recvOnly: true,  // 纯拉流模式，仅接收媒体流
  //   debug: false,  // 关闭调试日志
  //   audioEnable: true,  // 启用音频
  //   videoEnable: true   // 启用视频
  // })
  // if (player2) player.release()
  // player2 = new ZLMRTCClient.Endpoint({
  //   element: videoRef2.value,  // 绑定video元素
  //   zlmsdpUrl: videoAddress2.value,  // WebRTC流地址
  //   recvOnly: true,  // 纯拉流模式
  //   debug: false,  // 关闭调试日志
  //   audioEnable: true,  // 启用音频
  //   videoEnable: true   // 启用视频
  // })
});

// 组件卸载时释放资源
onBeforeUnmount(() => {
  if (checkInterval) clearInterval(checkInterval);
});
const markers = reactive([])
const mapContainer = ref(null)
let map;
let centerlnglat = [119.904792, 30.247956];
const loadAMap = async () => {
  // return new Promise((resolve, reject) => {
  //   if (window.AMap) {
  //     resolve(window.AMap);
  //     return;
  //   }
  //   const script = document.createElement('script');
  //   script.src = `https://webapi.amap.com/maps?v=2.0&key=ce77626588b7a2ee836159f48dd4a1a6`;
  //   script.addEventListener('load', () => resolve(window.AMap));
  //   script.onerror = reject;
  //   document.head.append(script);
  // });
  try {
    const AMap = await AMapLoader.load({
      key: mapSetting.mapKey,
      securityJsCode: mapSetting.mapSecurity,
      version: "2.0",
      plugins: [
        "AMap.AutoComplete",
        "AMap.ToolBar",
        "AMap.Scale",
        "AMap.Marker",
      ],
    });
    let marker;
    if (props.airportData && props.airportData.longitude) {
      centerlnglat = [props.airportData.longitude, props.airportData.latitude];
    }
    if (!map) {
      map = new AMap.Map(mapContainer.value, {
        zoom: 15,
        center: centerlnglat,
        pitch: 0, // 俯仰角度
        viewMode: '3D', // 启用 3D 模式
        layers: [
          // 卫星
          new AMap.TileLayer.Satellite(),
          // 路网
          new AMap.TileLayer.RoadNet(),
        ],
      });
    }
    if (props.airportData && props.airportData.longitude && props.airportData.latitude && AMap) {
      marker = new AMap.Marker({
        position: [props.airportData.longitude, props.airportData.latitude],
        title: props.airportData.airportName,
        icon: new AMap.Icon({
          // image: '../../../../../assets/airport_logo.png',
          image: getImageUrl('airport_logo.png'),
          size: new AMap.Size(48, 48),
          imageSize: new AMap.Size(48, 48),
        }),
        offset: new AMap.Pixel(-24, -24),
        autoRotation: false,
      })
      setTimeout(() => {
        if (map && marker) {
          map.add(marker);
          map.setFitView()
        }
      }, 1000);
    }
    // markers.push(marker)
  } catch (error) {
    console.error("地图初始化失败:", error);
    // ElMessage.error("地图初始化失败: " + error.message);
  }
};
const panelRef = ref(null);
onMounted(async () => {
  to_video()
  if (panelRef.value) {
    try {
      loadAMap();
    } catch (error) {
      console.error('地图加载失败:', error);
    }
  }
});
// onBeforeUnmount(() => {
// Object.values(hlsInstances).forEach((hls) => {
//   hls.destroy();
// });
// });
</script>
<template>
  <div class="air-map">
    <ElSplitter>
      <ElSplitterPanel size="65%" min="40%">
        <div class="videoBox">
          <div class="title"> 无人机监控直播
            <img class="icon" src="../../../../../assets/leftbg10.png" alt="" />
          </div>
          <div class="video" v-if="videoAddress">
            <webrtcPlayer :videoId="'videoRef'" :videoSrc="videoAddress" :controls="false">
              <!-- :fit="'scale-down'" -->
            </webrtcPlayer>
          </div>
        </div>
      </ElSplitterPanel>
      <ElSplitterPanel size="35%" min="30%">
        <ElSplitter layout="vertical">
          <ElSplitterPanel size="60%" min="50%">
            <div class="videoBox">
              <div class="title"> 机场监控直播
                <img class="icon" src="../../../../../assets/leftbg10.png" alt="" />
              </div>
              <div class="video" v-if="videoAddress2">
                <webrtcPlayer :videoId="'videoRef2'" :videoSrc="videoAddress2" :controls="false">
                </webrtcPlayer>
              </div>
            </div>
          </ElSplitterPanel>
          <ElSplitterPanel size="40%" min="10%" ref="panelRef">
            <div id="map-container" ref="mapContainer" class="map" style="height: 100%;">
            </div>
          </ElSplitterPanel>
        </ElSplitter>
      </ElSplitterPanel>
    </ElSplitter>
    <!-- <div class="air-left">
      <div class="videoBox">
        <div class="title"> 无人机监控直播
          <img class="icon" src="../../../../../assets/leftbg10.png" alt="" />
        </div>
        <div class="video" v-if="videoAddress">
          <webrtcPlayer :videoId="'videoRef'" :videoSrc="videoAddress" :controls="false"></webrtcPlayer>
        </div>
      </div>
    </div> -->
    <!-- <div class="air-right">
      <div class="air-top">
        <div class="videoBox">
          <div class="title"> 机场监控直播
            <img class="icon" src="../../../../../assets/leftbg10.png" alt="" />
          </div>
          <div class="video" v-if="videoAddress2">
            <webrtcPlayer :videoId="'videoRef2'" :videoSrc="videoAddress2" :controls="false"></webrtcPlayer>
          </div>
        </div>
      </div>
      <div class="air-bottom">
        <div id="map-container" ref="mapContainer" class="map"></div>
      </div>
    </div> -->
  </div>
</template>

<style lang="scss" scoped>
:deep(.amap-logo) {
  display: none !important;
}

:deep(.amap-copyright) {
  display: none !important;
}

:deep(.el-splitter-bar__dragger:before) {
  background-color: #023b3f;
}

.air-map {
  // margin: 10px;
  display: flex;
  height: 100%;
  width: 100%;

  // .air-left {
  //   width: calc(65% - 2vh);
  //   // height: 675px;
  //   margin: 1vh 0 1vh 1vh;
  //   box-sizing: border-box;
  //   border: 0.1 solid #023337;
  //   overflow: hidden;

  .videoBox {
    position: relative;
    width: 100%;
    height: 100%;

    .title {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 4vh;
      padding-left: 1.5vh;
      margin: 0;
      font-family: PingFangSC, 'PingFang SC';
      font-size: 2vh;
      font-style: normal;
      font-weight: 500;
      color: #fffefe;
      user-select: none;
      background: radial-gradient(ellipse 140% 300% at 100% 50%,
          rgba(1, 34, 35, 0.2) 28%,
          rgba(7, 217, 221, 0.7) 100%);

      .icon {
        width: 3vh;
        margin-right: 1vw;
      }
    }

    .video {
      width: 100%;
      height: calc(100% - 4vh);
      background-color: #000000;
      object-fit: fill;
    }

    // :deep(.video-wrapper) {
    //   width: 100%;
    //   height: 100%;
    //   padding-bottom: 0 !important;
    // }
  }

  // border: 1px solid #fff;
  .img {
    width: 100%;
    height: 100%;
    -webkit-user-drag: none;
    user-select: none;
  }

  // }

  // .air-right {
  //   width: calc(35% - 1vh);
  //   // height: 675px;
  //   margin: 1vh 0 1vh 1vh;
  //   overflow: hidden;

  // .air-top {
  //   clear: both;
  //   width: 100%;
  //   height: calc(50% - 1vh);

  // border: 1px solid #fff;
  .img {
    width: 100%;
    height: 100%;
    -webkit-user-drag: none;
    user-select: none;
  }

  .videoBox {
    position: relative;
    width: 100%;
    height: 100%;

    .title {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 4vh;
      padding-left: 1.5vh;
      margin: 0;
      font-family: PingFangSC, 'PingFang SC';
      font-size: 2vh;
      font-weight: 500;
      color: #fffefe;
      user-select: none;
      background: radial-gradient(ellipse 140% 300% at 100% 50%,
          rgba(1, 34, 35, 0.2) 28%,
          rgba(7, 217, 221, 0.7) 100%);

      .icon {
        width: 3vh;
        margin-right: 1vw;
      }
    }

    .video {
      width: 100%;
      height: calc(100% - 4vh);
      background-color: #000000;
      object-fit: fill;
    }

    // :deep(.video-wrapper) {
    //   width: 100%;
    //   height: 100%;
    //   padding-bottom: 0 !important;
    // }
  }

  // }

  // .air-bottom {
  //   width: 100%;
  //   height: calc(50%);
  //   margin-top: 1vh;

  // border: 1px solid #fff;
  .img {
    width: 100%;
    height: 100%;
    -webkit-user-drag: none;
    user-select: none;
  }

  .map {
    width: 100%;
    height: 100%;
  }

  // }
}
</style>
